/**
 * Created by sky on 2019/3/11.
 */
var baseExtend = "../../script/";

layui.define(['zepto'], function (exports) {
    layui.config({
        base: baseExtend
    }).use(['storage'], function () {
        var $ = layui.zepto;
        var imid = getParam('imid');
        var storage = layui.storage(imid);
        // var initUI_justchat = function () {
        //     //重置标题栏背景 (直接改源码对应的标题颜色)
        //     //$(".layim-title").css("background-color", "#2a80fc");
        //     // debugger
        //
        //     $("#layui-m-layer0 .layim-chat-status")
        //         .css("position", "absolute")
        //         .css("left", "45%")
        //         .css("font-color", "#ffffff")
        //         .css("font-size", "20px")
        //         .css("opacity", "1")
        //         .html('消息<span class="layim-msg-new">7</span>');
        //     $(".layui-layim-tab").hide();
        // };
        function getParam(paramName) {
            var paramValue = "", isFound = !1;
            if (window.location.search.indexOf("?") == 0 && window.location.search.indexOf("=") > 1) {
                var arrSource = unescape(window.location.search).substring(1, window.location.search.length).split("&"), i = 0;
                while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
            }
            return paramValue == "" && (paramValue = null), paramValue
        };

        var uuid = function () {
            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";

            var uuid = s.join("");
            return uuid;
        };

        var initPicEvent = function (layim) {
            $("#justchat_uploadPic").unbind("change").bind("change", function () {
                //debugger;
                var files = this.files;

                for (var i = 0; i < files.length; i++) {
                    var cid = uuid();
                    layim.beforePicUpload(cid);
                    if(window.socketState != 'success'){
                        layer.msg('图片上传失败，当前网络未连接！');
                        return
                    }
                    uploadQiniu(files[i], layim, cid)
                }
            });
        };

        var uploadQiniu = function (file, layim, cid) {
            layui.config({
                base: '../../script/'
            }).use(['justchatApiMgr'], function () {
                var config = {
                    useCdnDomain: true,
                    disableStatisticsReport: false,
                    retryCount: 6
                };
                var putExtra = {
                    fname: "",
                    params: {},
                    mimeType: null
                };

                var justchatApiMgr = layui.justchatApiMgr;
                var onSucceedCallback = function (result) {
                    console.log("token=" + result.data.token);
                    console.log("key=" + result.data.key);
                    var token = result.data.token;
                    var key = result.data.key;
                    var observable = qiniu.upload(file, key, token, putExtra, config);
                    var subObject = {
                        next: function (response) {

                        },
                        error: function (err) {
                            // 发送失败
                            $('#chat-' + cid).find('.layim-chat-loading').remove();
                            layer.msg('图片上传失败，请重试！');
                        },
                        complete: function (res) {
                            // 删除默认图的聊天历史；
                            var target_id = getParam('target_id') || sessionStorage.getItem('target').id || window.currentTarget;
                            if(!target_id) throw new Error('target_id不存在');
                            var chatlogs = storage.getChatlogById(target_id);
                            var len = chatlogs.length;
                            for(var i=len-1;i>=0;i--){
                                if(chatlogs[i].cid == cid){
                                    storage.deleteChatlogById({
                                        id:target_id,
                                        index:i
                                    })
                                    break;
                                }
                            }

                            getPicUrlFunc(justchatApiMgr, key, layim, cid);
                        }
                    };
                    var subscription = observable.subscribe(subObject);
                };
                justchatApiMgr.getToken(onSucceedCallback);
            });
        }

        var getPicUrlFunc = function (justchatApiMgr, key, layim, cid) {
            var onSucceedCallback = function (result) {
                var data = result.data;
                var urls = data.urls;

                if (!(urls && urls[0] && urls[0].url)) {
                    layer.msg('图片上传失败，请重试！');
                    return
                }

                var url = (/[0-9]{4}\/[0-9]{2}\/[0-9]{2}\/.+/g.exec(urls[0].url))[0];
                if (url) {
                    layim.addPicToChat(url, cid);
                } else {
                    layer.msg('图片上传失败，请重试！');
                    return
                }
            };
            justchatApiMgr.getURL(key, onSucceedCallback, function () {
                layer.msg('图片上传失败，请重试！');
                return
            });
        };

        // var sendPicToChat = function (url) {
        //     debugger
        //     console.log(url)
        // };

        var getReturnTitle = function () {
            return '<i class="layui-icon layim-chat-back" layim-event="back"></i>返回<span class="layim-chat-status"></span>';
        };

        // var updateChatStatus = function (status) {
        //     if (status == "ONLINE") {
        //         $(".justchat-status").html('<cite class="layui-icon layim-status-online"></cite>当前在线');
        //     } else if (status == "OFFLINE") {
        //         $(".justchat-status").html('<cite class="layui-icon layim-status-hide"></cite>下线');
        //     } else if (status == "BUSY") {
        //         $(".justchat-status").html('<cite class="layui-icon layim-status-hide"></cite>休息离开');
        //     } else if (status == "DISABLE") {
        //         $(".justchat-status").html('<cite class="layui-icon layim-status-hide"></cite>禁用');
        //     }
        // };

        var obj = {
            // initUI_justchat: initUI_justchat,
            getReturnTitle: getReturnTitle,
            // updateChatStatus: updateChatStatus,
            initPicEvent: initPicEvent
        };

        exports('uiextend', obj);

    })
});